library KWLib;

{ Important note about DLL memory management: ShareMem must be the
  first unit in your library's USES clause AND your project's (select
  Project-View Source) USES clause if your DLL exports any procedures or
  functions that pass strings as parameters or function results. This
  applies to all strings passed to and from your DLL--even those that
  are nested in records and classes. ShareMem is the interface unit to
  the BORLNDMM.DLL shared memory manager, which must be deployed along
  with your DLL. To avoid using BORLNDMM.DLL, pass string information
  using PChar or ShortString parameters. }

uses
  {$IFDEF RELEASE}
  EurekaLog,
  {$ENDIF}
  {$IFDEF DEBUG}
  FastMM4,
  {$ENDIF}
  Windows,
  SysUtils,
  Classes,
  kwStrings;

type
  PDllGlobalData = ^TDllGlobalData;
  TDllGlobalData = packed record
    HookHandle : HWND;
  end;

var
  DllData : PDllGlobalData;
  MMFHandle : THandle;
  WM_KEYBOARDHOOK : Cardinal;

const
  DllGlobalDataName = 'KWLibData';

{$R *.res}

function KeyboardHookProc(Code : Integer; wParam : WPARAM;
  lParam : LPARAM) : LRESULT; stdcall;
begin
  if (Code = HC_ACTION) then
    PostMessage(HWND_BROADCAST, WM_KEYBOARDHOOK, wParam, lParam);
    //PostMessage(HWND_BROADCAST, WM_KEYBOARDHOOK, wParam, GetKeyboardLayout(0));

  Result := CallNextHookEx(DllData^.HookHandle, Code, wParam, lParam);
end;

procedure SetHook; stdcall;
begin
  DllData^.HookHandle :=
    SetWindowsHookEx(WH_KEYBOARD, @KeyboardHookProc, HInstance, 0);

  if (DllData^.HookHandle = 0) then
    raise Exception.Create(rsSetKeyboardHookFailed);
end;

procedure RemoveHook; stdcall
begin
  if not UnhookWindowsHookEx(DllData^.HookHandle) then
    raise Exception.Create(rsUnSetKeyboardHookFailed);
end;

procedure InitializeMMF;
begin
  WM_KEYBOARDHOOK := RegisterWindowMessage('WM_KEYBOARDHOOK');

  MMFHandle := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE,
    0, SizeOf(TDllGlobalData), DllGlobalDataName);

  if (MMFHandle = 0) then
    raise Exception.Create(rsMMFCreateError);

  DllData := MapViewOfFile(MMFHandle, FILE_MAP_ALL_ACCESS, 0, 0,
    SizeOf(TDllGlobalData));
  if DllData = nil then
  begin
    CloseHandle(MMFHAndle);
    raise Exception.Create(rsMMFMapInitError);
  end;
end;

procedure UnInitializeMMF;
begin
  UnmapViewOfFile(DllData);
  CloseHandle(MMFHandle);
end;

procedure DllEntryPoint(dwReason : DWord);
begin
  case dwReason of
    DLL_PROCESS_ATTACH : InitializeMMF;
    DLL_PROCESS_DETACH : UnInitializeMMF;
  end;
end;

exports
  SetHook,
  RemoveHook;

begin
  DllProc := @DllEntryPoint;
  DllEntryPoint(DLL_PROCESS_ATTACH);
end.
